package cn.acewill.yxd.yunxundian.ui.user;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.adapter.messageNoticeRecycleAdapter;
import cn.acewill.yxd.yunxundian.model.MessageBean;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;


/**
 * Created by XXX on 2017/4/2.
 */
public class MessageNoticeActivity extends BaseActivity {

    private RecyclerView msgWarmList;
    private TextView noNetWork;
    private TextView nomsg;
    private messageNoticeRecycleAdapter adapter;
    private ArrayList<MessageBean> msgList;
    private RelativeLayout loadingRel;
    private String type;
    //点击后赋值于此
    private MessageBean msgBean;
    //记录更改的次数
    private int count=0;
    private int msgType;
    private Handler mHandler = new MyHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message_warm_list);
        initView();
    }

    public void initView(){
        msgType=getIntent().getIntExtra("label",-1);
        Toolbar mytoolbar = (Toolbar) findViewById(R.id.myToolBar);
        mytoolbar.setTitle("");
        mytoolbar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(mytoolbar);
        mytoolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送广播
                Intent in=new Intent();
                in.setAction(MainActivity.MESSAGE_UNREAD);
                in.putExtra("count",count);
                MessageNoticeActivity.this.sendBroadcast(in);
                finish();
            }
        });
        loadingRel= (RelativeLayout) findViewById(R.id.loadingRel);
        TextView titleName = (TextView) findViewById(R.id.titleName);
        titleName.setText("消息详情");
        this.noNetWork= (TextView) findViewById(R.id.noNetWork);
        noNetWork.setOnClickListener(new View.OnClickListener() { //去设置页面
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        this.msgWarmList= (RecyclerView)findViewById(R.id.msgWarmList);
        //开始
        this.nomsg= (TextView) findViewById(R.id.nomsg);
        setVisibleOrGone(1);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(OrientationHelper.VERTICAL);
        msgWarmList.setLayoutManager(manager);
    }

    private static class MyHandler extends Handler{
        private WeakReference<MessageNoticeActivity> mActivity;
        MyHandler(MessageNoticeActivity activity){
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                mActivity.get().noNetWork.setVisibility(View.GONE);
                switch (mActivity.get().msgType){
                    case 1:
                        mActivity.get().type="yichang";
                        mActivity.get().LoadUnNormalMsg();
                        break;
                    case 2:
                        mActivity.get().type="xiaoxi";
                        mActivity.get().loadNormalMsg();
                        break;
                    case 3:
                        mActivity.get().type="gonggao";
                        mActivity.get().LoadNoticeMsg();
                        break;
                }
            }else{
                mActivity.get().setVisibleOrGone(3);
            }
        }
    }
    /**
     * 加载消息提醒
     */
    public void loadNormalMsg(){
        Map<String,Object> map=new HashMap<>();
        map.put("empid", MainActivity.id);
        map.put("task","loadMsgByType");
        map.put("type","xiaoxi");
        pubClass.Post(pubClass.Server_namehzm,map, new pubClass.MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                String[] arry =result.split("\\|");
                if (arry[3].length()>2){
                    //有值则进行解析
                    setVisibleOrGone(2);
                    Gson gson = new Gson();
                    Type typeList=new TypeToken<ArrayList<MessageBean>>(){
                    }.getType();
                    msgList=gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                    adapter = new messageNoticeRecycleAdapter(MessageNoticeActivity.this, msgList, new messageNoticeRecycleAdapter.LookCliclListener() {
                        @Override
                        public void lookOnclick(int position) {
                            msgBean=msgList.get(position);
                            if (msgBean.getIsread()==0){
                                updateStatus();
                            }
                                Intent in=new Intent(MessageNoticeActivity.this,MessageNoticDetailActivity.class);
                                in.putExtra("title",msgBean.getTitle());
                                in.putExtra("msg",msgBean.getMsg());
                                startActivity(in);
                        }
                    });
                    msgWarmList.setAdapter(adapter);
                }else {
                    //无则显示无任何消息
                    setVisibleOrGone(4);
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });
    }

    public void LoadUnNormalMsg(){
        Map<String,Object> map=new HashMap<>();
        map.put("empid", MainActivity.id);
        map.put("task","loadMsgByType");
        map.put("type","yichang");

        pubClass.Post(pubClass.Server_namehzm,map, new pubClass.MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                String[] arry =result.split("\\|");
                if (arry[3].length()>2){
                    setVisibleOrGone(2);
                    //有值则进行解析
                    Gson gson = new Gson();
                    Type typeList=new TypeToken<ArrayList<MessageBean>>(){
                    }.getType();
                    msgList=gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                    adapter = new messageNoticeRecycleAdapter(MessageNoticeActivity.this, msgList, new messageNoticeRecycleAdapter.LookCliclListener() {
                        @Override
                        public void lookOnclick(int position) {
                            msgBean=msgList.get(position);
                            if (msgBean.getIsread()==0){
                                updateStatus();
                            }
                            Intent in=new Intent(MessageNoticeActivity.this,MessageNoticDetailActivity.class);
                            in.putExtra("title",msgBean.getTitle());
                            in.putExtra("msg",msgBean.getMsg());
                            startActivity(in);
                        }
                    });
                    msgWarmList.setAdapter(adapter);
                }else{
                   setVisibleOrGone(4);
                }

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });
    }

    /**
     * 加载公告数据
     */
    public void LoadNoticeMsg(){
        Map<String,Object> map=new HashMap<>();
        map.put("empid", MainActivity.id);
        map.put("task","loadMsgByType");
        map.put("type","gonggao");
        pubClass.Post(pubClass.Server_namehzm,map, new pubClass.MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                String[] arry = result.split("\\|");
                if (arry[3].length()>2){
                    setVisibleOrGone(2);
                    //有值则进行解析
                    Gson gson = new Gson();
                    Type typeList=new TypeToken<ArrayList<MessageBean>>(){
                    }.getType();
                    msgList=gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                    adapter = new messageNoticeRecycleAdapter(MessageNoticeActivity.this, msgList, new messageNoticeRecycleAdapter.LookCliclListener() {
                        @Override
                        public void lookOnclick(int position) {
                            msgBean=msgList.get(position);
                            if (msgBean.getIsread()==0){
                                updateStatus();
                            }
                            Intent in=new Intent(MessageNoticeActivity.this,MessageNoticDetailActivity.class);
                            in.putExtra("title",msgBean.getTitle());
                            in.putExtra("msg",msgBean.getMsg());
                            startActivity(in);
                        }
                    });
                    msgWarmList.setAdapter(adapter);
                }else{
                    setVisibleOrGone(4);
                }

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });
    }


    //点击更新状态
    public void updateStatus(){
        Map<String,Object> map=new HashMap<>();
        map.put("empid", MainActivity.id);
        map.put("task","readMsgByType");
        map.put("type",type);
        map.put("msgid",msgBean.getID());
        pubClass.Post(pubClass.Server_namehzm,map,new pubClass.MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                msgBean.setIsread(1);
                adapter.notifyDataSetChanged();
                count++;
                if (type.equals("yichang")){
                    Intent in=new Intent().putExtra("count",count);
                    setResult(1001,in);
                }
                if (type.equals("xiaoxi")){
                    Intent in=new Intent().putExtra("count",count);
                    setResult(1002,in);
                }
                if (type.equals("gonggao")){
                    Intent in=new Intent().putExtra("count",count);
                    setResult(1003,in);
                }

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            //发送广播
            Intent in=new Intent();
            in.setAction(MainActivity.MESSAGE_UNREAD);
            in.putExtra("count",count);
            sendBroadcast(in);
            finish();
        }
    return false;
    }


    //接受网络状态的判断广播
   NetWorkStateReceiver netWorkStateReceiver;
    int whetherConnectNetWork=0;
    @Override
    protected void onResume() {
        if (netWorkStateReceiver==null){
            netWorkStateReceiver=new NetWorkStateReceiver();
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver,filter);
        System.out.print("广播注册");
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkStateReceiver);
        System.out.print("广播注销");
    }

    class NetWorkStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            assert mConnectivityManager != null;
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            whetherConnectNetWork=(mNetworkInfo==null)?0:1;
            Message msg=new Message();
            msg.what=whetherConnectNetWork;
            mHandler.sendMessage(msg);
        }
    }

    public void setVisibleOrGone(int k){

        if (k ==1){//初始化进入页面
            nomsg.setVisibility(View.GONE);
            msgWarmList.setVisibility(View.GONE);
            noNetWork.setVisibility(View.GONE);

        }
        if (k==2){//数据请求成功
           loadingRel.setVisibility(View.GONE);
            nomsg.setVisibility(View.GONE);
            noNetWork.setVisibility(View.GONE);
            msgWarmList.setVisibility(View.VISIBLE);
        }
        if (k==3){//无网络状态时
            loadingRel.setVisibility(View.GONE);
            noNetWork.setVisibility(View.VISIBLE);
            msgWarmList.setVisibility(View.GONE);
            nomsg.setVisibility(View.GONE);
        }
        if (k==4){//无数据
            loadingRel.setVisibility(View.GONE);
            noNetWork.setVisibility(View.GONE);
            msgWarmList.setVisibility(View.GONE);
            nomsg.setVisibility(View.VISIBLE);
        }


    }

}
